package com.sf.tools.common;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class PrintUtil {

	private static void updateTextArea(final JTextArea textArea,final String text) {
		SwingUtilities.invokeLater(new Runnable() {

			public void run() {
				textArea.append(text);
			}
		});
	}

	public static void redirectSystemStreams(final JTextArea textArea, final String lOG_MARK) {
		OutputStream out = new OutputStream() {

			@Override
			public void write(int b) throws IOException {
				updateTextArea(textArea, String.valueOf((char) b));
			}

			@Override
			public void write(byte[] b, int off, int len) throws IOException {
				String text = new String(b, off, len);
				if(text.startsWith(lOG_MARK)){
					text = text.replace(lOG_MARK, "");
					updateTextArea(textArea, text);
				}else if("\r\n".equals(text)){
					updateTextArea(textArea, text);
				}
			}

			@Override
			public void write(byte[] b) throws IOException {
				write(b, 0, b.length);
			}
		};

		System.setOut(new PrintStream(out, true));
		System.setErr(new PrintStream(out, true));
	}

}
